import { createStore } from "vuex";
import axios from "axios";

const store = createStore({
  state() {
    return {
      curEditId: 0, // 当前处于编辑状态的 todo Id
      curStatus: "All", // 当前状态， All Active Completed
      todos: [], // 待办事项
    };
  },

  getters: {
    todoLen(state) {
      return state.todos.length;
    },

    displayTodos(state) {
      switch (state.curStatus) {
        case "Active":
          return state.todos.filter((item) => !item.completed);

        case "Completed":
          return state.todos.filter((item) => item.completed);

        default:
          return state.todos;
      }
    },

    showClear(state) {
      return state.todos.filter((item) => item.completed).length > 0;
    },
  },

  mutations: {
    setTodos(state, payload) {
      state.todos = payload;
    },

    setCurEditId(state, payload) {
      state.curEditId = payload;
    },

    setCurStatus(state, payload) {
      state.curStatus = payload;
    },
  },

  actions: {
    /**
     * 获取待办事项
     */
    getTodoList({ commit }) {
      axios.get("http://localhost:3000/todos").then(({ data }) => {
        // 提交 setTodos
        commit("setTodos", data);
      });
    },

    /**
     * 添加
     *    payload 就是一个 title
     */
    addTodo({ dispatch, state, commit }, payload) {
      // 非空检验
      if (!payload) return;

      axios
        .post("http://localhost:3000/todos", {
          title: payload,
          completed: false,
        })
        .then((response) => {
          console.log("新增成功", response);

          // 方案一：重新获取数据库最新数据 getTodoList
          // dispatch("getTodoList");

          // 方案二：不重新调用接口的方式
          //    1. 追加 response.data 到 现有的 todos 中
          //        不要直接修改 state 的数据，只能通过 mutation
          // state.todos.push(response.data);
          commit("setTodos", [...state.todos, response.data]);
        });
    },

    /**
     * 删除
     */
    delTodo({ dispatch, commit, state }, id) {
      if (!id) return;

      const url = `http://localhost:3000/todos/${id}`;
      axios.delete(url).then((response) => {
        console.log("删除成功");

        // dispatch("getTodoList");
        commit(
          "setTodos",
          state.todos.filter((item) => item.id !== id)
        );
      });
    },

    /**
     * 多个删除
     *    ids [1, 2, 3]
     */
    delBatchTodo({ commit, state }, ids) {
      if (ids.length <= 0) return;

      // JSON-SERVER 启动的接口，不支持批量删除，可以循环调用多次接口
      //    并行 or 串行

      Promise.all(
        ids.map((item) => axios.delete(`http://localhost:3000/todos/${item}`))
      ).then((response) => {
        console.log("全部删除成功");

        commit(
          "setTodos",
          state.todos.filter((item) => !ids.includes(item.id))
        );
      });
    },

    /**
     * 批量更新勾选状态
     *    completed:  true | false
     *
     */
    updateBatchTodo({ commit, state }, completed) {
      Promise.all(
        state.todos.map((item) =>
          axios.patch(`http://localhost:3000/todos/${item.id}`, {
            completed,
          })
        )
      ).then((response) => {
        console.log("全部删除成功");

        commit(
          "setTodos",
          state.todos.map((item) => ({
            ...item,
            completed,
          }))
        );
      });
    },

    /**
     * 更新
     *    payload 就是一个最新的 todo {id, title, completed}
     */
    updateTodo({ commit, state }, { id, ...rest }) {
      const url = `http://localhost:3000/todos/${id}`;

      axios.patch(url, rest).then((response) => {
        console.log("更新成功");

        commit("setCurEditId", 0);

        commit(
          "setTodos",
          state.todos.map((item) => {
            if (item.id === id) {
              return response.data;
            } else {
              return item;
            }
          })
        );
      });
    },
  },
});

export default store;
